package org.jeecg.modules.wmhb.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * @Description: 合同表
 * @Author: jeecg-boot
 * @Date: 2024-09-02
 * @Version: V1.0
 */
@Tag(name = "合同表")
@RestController
@RequestMapping("/wmhb/wmContract")
@Slf4j
public class WmContractController extends JeecgController<WmContract, IWmContractService> {
    @Autowired
    private IWmContractService wmContractService;
    @Autowired
    private IWmProjectService wmProjectService;
    @Autowired
    private IWmContractProductService wmContractProductService;
    @Autowired
    private IWmClientService wmClientService;

    /**
     * 分页列表查询
     *
     * @param wmContract
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "合同表-分页列表查询")
    @Operation(summary = "合同表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmContract>> queryPageList(WmContract wmContract,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<WmContract> queryWrapper = QueryGenerator.initQueryWrapper(wmContract, req.getParameterMap());
        Page<WmContract> page = new Page<WmContract>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        IPage<WmContract> pageList = wmContractService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmContract
     * @return
     */
    @AutoLog(value = "合同表-添加")
    @Operation(summary = "合同表-添加")
    @RequiresPermissions("wmhb:wm_contract:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmContract wmContract) {
        if (UserConstant.NOT_UNIQUE.equals(wmContractService.checkCodeUnique(wmContract))) {
            return Result.error("新增合同失败，合同编码已存在");
        }
        if (UserConstant.NOT_UNIQUE.equals(wmContractService.checkNameUnique(wmContract))) {
            return Result.error("新增合同失败，合同名称已存在");
        }

        if (StringUtils.isEmpty(wmContract.getCode())) {
            String code = (String) FillRuleUtil.executeRule(FillRuleConstant.CONTRACT, null);
            wmContract.setCode(code);
        }

        if (StringUtils.isEmpty(wmContract.getWeight())) {
            wmContract.setWeight("1");
        }

        WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
        if (wmProject != null && wmProject.getStatus().equals(UserConstant.PROJECT_STATUS_PREPARE)) {
            return Result.error("请先确认项目");
        }

        wmContractService.save(wmContract);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmContract
     * @return
     */
    @AutoLog(value = "合同表-编辑")
    @Operation(summary = "合同表-编辑")
    @RequiresPermissions("wmhb:wm_contract:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmContract wmContract) {
        if (UserConstant.NOT_UNIQUE.equals(wmContractService.checkCodeUnique(wmContract))) {
            return Result.error("编辑合同" + wmContract.getCode() + "失败，合同编码已存在");
        }
        if (UserConstant.NOT_UNIQUE.equals(wmContractService.checkNameUnique(wmContract))) {
            return Result.error("编辑合同" + wmContract.getCode() + "失败，合同名称已存在");
        }

        if (StringUtils.isEmpty(wmContract.getWeight())) {
            wmContract.setWeight("1");
        }

        wmContractService.updateById(wmContract);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "合同表-通过id删除")
    @Operation(summary = "合同表-通过id删除")
    @RequiresPermissions("wmhb:wm_contract:delete")
    @DeleteMapping(value = "/delete")
    @Transactional
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        if (wmContractService.checkHasItem(id)) {
            return Result.error("合同下有任务书，请先删除任务书");
        }
        wmContractService.removeById(id);
        wmContractProductService.removeByWmContractId(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "合同表-批量删除")
    @Operation(summary = "合同表-批量删除")
    @RequiresPermissions("wmhb:wm_contract:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> oldIdList = Arrays.asList(ids.split(","));//前端参数
        List<String> newIdList = new ArrayList<>();   //可以删除的ID列表
        List<String> filterIdList = new ArrayList<>();//不能删除的ID列表
        for (String id : oldIdList) {
            if (!wmContractService.checkHasItem(id)) {
                newIdList.add(id);
            } else {
                filterIdList.add(id);
            }
        }

        String filterStr = String.join(",", filterIdList);
        if (!CollectionUtils.isEmpty(newIdList)) {
            wmContractService.removeByIds(newIdList);
            for (String id : newIdList) {
                wmContractProductService.removeByWmContractId(id);
            }

            if (CollectionUtils.isEmpty(filterIdList)) {
                return Result.OK("批量删除成功！");
            } else {
                String newStr = String.join(",", newIdList);
                return Result.OK("ID为" + newStr + "批量删除成功，ID为" + filterStr + "的删除失败，原因：合同下有任务书！");
            }
        } else {
            return Result.error("批量删除失败，原因：合同下有任务书！");
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "合同表-通过id查询")
    @Operation(summary = "合同表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmContract> queryById(@RequestParam(name = "id", required = true) String id) {
        WmContract wmContract = wmContractService.getById(id);
        if (wmContract == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmContract);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wmContract
     */
    @RequiresPermissions("wmhb:wm_contract:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmContract wmContract) {
        List<WmContract> wmContractList = wmContractService.listBySearch(wmContract);
        return wmContractService.exportContractExcel(request, wmContractList);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("wmhb:wm_contract:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WmContract.class);
    }

    /**
     * 确认
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "合同表-确认")
    @Operation(summary = "合同表-确认")
    @RequiresPermissions("wmhb:wm_contract:confirm")
    @RequestMapping(value = "/confirm", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> doConfirm(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            WmContract wmContract = wmContractService.getById(id);
            if (!wmContract.getStatus().equals(UserConstant.CONTRACT_STATUS_PREPARE)) {
                {
                    throw new RuntimeException("只有草稿状态能确认");
                }
            }

            //wmContract.setProgress("10");
            wmContract.setStatus(UserConstant.CONTRACT_STATUS_CONFIRMED); //更新合同的状态
            wmContractService.updateById(wmContract);
        }
        return Result.OK("操作成功");
    }

    /**
     * 完成
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "合同表-完成")
    @Operation(summary = "合同表-完成")
    @RequiresPermissions("wmhb:wm_contract:finish")
    @Transactional
    @RequestMapping(value = "/finish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> doFinish(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            WmContract wmContract = wmContractService.getById(id);
            if (!wmContract.getStatus().equals(UserConstant.CONTRACT_STATUS_CONFIRMED)) {
                {
                    throw new RuntimeException("只有确认状态能确认");
                }
            }

            wmContract.setProgress("100");
            wmContract.setStatus(UserConstant.PROJECT_STATUS_FINISHED); //更新项目的状态
            wmContractService.updateById(wmContract);
        }
        return Result.OK("操作成功");
    }

    /**
     * 执行合同将合同产品最小销售单位生成计划
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "合同表-执行合同")
    @Operation(summary = "合同表-执行合同")
    //@RequiresPermissions("wmhb:wm_contract:execute")
    @RequestMapping(value = "/execute", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> doExecute(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            WmContract wmContract = wmContractService.getById(id);
            if (!wmContract.getStatus().equals(UserConstant.CONTRACT_STATUS_CONFIRMED)) {
                {
                    throw new RuntimeException("只有确认状态能执行合同");
                }
            }

            wmContract.setStatus(UserConstant.CONTRACT_STATUS_CONFIRMED);
            wmContractService.executeContract(wmContract);
        }
        return Result.OK("操作成功");
    }
}
